<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '128M');

require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';

$g_start = microtime(true);

$dbconn = Connection::getInstance();

while(true) 
{
	if ($emails = getEmail($dbconn)) {
		foreach ($emails as $email)
		{
			updateEmailById($email['id'], $email['created'], $email['open_time'], $email['sent'], $dbconn);
		}
	} else {
		exit('failed or completed');
	}
}

function getEmail(Connection $db)
{
	$sql = "SELECT id, created, open_time, sent FROM `emails` where sent_date = '0000-00-00 00:00:00' limit 100";
	try{
		$ret = $db->query($sql);
		if (count($ret) > 0) {
			return $ret;
		}
		return false;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function updateEmailById($id, $created, $open_time, $sent, $db) {
	$sql = "update `emails` set created_date=?, open_time_date=?, sent_date=? where id=?";
	try{
		$ret = $db->execute($sql, array(date('YmdHis', $created), date('YmdHis', $open_time), date('YmdHis', $sent), $id));
		return $ret;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}